package com.example.administrator.footballgamecollectandanalyze;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import bean.MyTeam_name;
import tool.MyApplication;

public class CreateGame extends AppCompatActivity {
    private int mYear, mMonth, mDay,mHours,mMinutes;
    private TextView Location;
    private TextView dateDisplay;
    final int DATE_DIALOG = 1;
    final int Time_DIALOG = 2;
    private Button btnTimePick;
    private Spinner spiChooseTeam;
    private List<String> Teamname;
    private ArrayAdapter<String> arr_adapter;
    private MyApplication app;
    private Button StartGame;

    String url = "http://112.74.26.238:8080/football/creatteam";
    String url1 = "http://112.74.26.238:8080/football/creatteam1";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_game);

        btnTimePick = (Button) findViewById(R.id.TimePick);
        dateDisplay = (TextView) findViewById(R.id.dateDisplay);
        spiChooseTeam = (Spinner) findViewById(R.id.ChooseTeam);
        StartGame = (Button) findViewById(R.id.StartGame);
        Location = (TextView) findViewById(R.id.Location);

        btnTimePick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog(DATE_DIALOG);
                showDialog(Time_DIALOG);
            }
        });

        app = (MyApplication) getApplication();
        String UserName = app.getMana_id();

        Teamname = new ArrayList<String>();
        loginByAsyncHttpClientPost(UserName);

        //适配器
        arr_adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Teamname);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spiChooseTeam.setAdapter(arr_adapter);
        StartGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String TeamName = (String) spiChooseTeam.getSelectedItem();
                String GameTime = dateDisplay.getText().toString();// 用户密码
                String Location1 = Location.getText().toString();
                //判断用户名和密码是否为空
                if (TextUtils.isEmpty(Location1.trim())) {
                    Toast.makeText(CreateGame.this, "请填写地址", Toast.LENGTH_LONG).show();
                }else if (GameTime.equals("xxxx-xx-xx-xx:xx"))
                {
                    Toast.makeText(CreateGame.this, "请选择时间", Toast.LENGTH_LONG).show();
                }
                else
                {
                    String Mana_id_main = app.getMana_id();
                    CreateTeamByAsyncHttpClientPost(TeamName, Mana_id_main,GameTime,Location1);
                }
            }
        });

        final Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        mHours = ca.get(Calendar.HOUR);
        mMinutes = ca.get(Calendar.MINUTE);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
            case Time_DIALOG:
                return new TimePickerDialog(this, mTimeListener,mHours,mMinutes,true);
        }
        return null;
    }

    public void display() {
        dateDisplay.setText(new StringBuffer().append(mYear).append(mMonth + 1).append("-").append(mDay).append("    ").append(mHours).append(":").append(mMinutes).append(" "));
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display();
        }
    };

    private TimePickerDialog.OnTimeSetListener mTimeListener =new  TimePickerDialog.OnTimeSetListener(){
        @Override
        public void onTimeSet(TimePicker view,int hour,int minutes){
            mHours= hour;
            mMinutes= minutes;
        }
    };
    public void loginByAsyncHttpClientPost(final String userName) {
        AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
        // 创建请求参数的封装的对象
        RequestParams params = new RequestParams();
        params.put("username", userName); // 设置请求的参数名和参数值

        // 执行post方法
        RequestHandle post = client.get(url, params, new AsyncHttpResponseHandler() {
            /**
             * 成功处理的方法
             * statusCode:响应的状态码; headers:相应的头信息 比如 响应的时间，响应的服务器 ;
             * responseBody:响应内容的字节
             */
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  byte[] responseBody) {
                if (statusCode == 200) {
                    String str = new String(responseBody);
                    if (str.equals("error")) {
                            Toast.makeText(CreateGame.this,"您还没有球队先创建球队",Toast.LENGTH_SHORT).show();
                    } else {
                        Gson gson = new Gson();
                        List<MyTeam_name> list = new ArrayList<MyTeam_name>();
                        list = gson.fromJson(str,new TypeToken<ArrayList<MyTeam_name>>(){}.getType());
                        Teamname.clear();
                        for (int i = 0; i < list.size(); i++) {
                            Teamname.add(list.get(i).getTeam_name());
                        }
                        arr_adapter.notifyDataSetChanged();
                    }
                }
            }

            /**
             * 失败处理的方法
             * error：响应失败的错误信息封装到这个异常对象中
             */
            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  byte[] responseBody, Throwable error) {
                error.printStackTrace();// 把错误信息打印出轨迹来
                //Toast.makeText(MyApplication.getContext(), "网络错误", Toast.LENGTH_LONG).show();
            }
        });
    }

    public void CreateTeamByAsyncHttpClientPost(String TeamName,String Mana_id_main, String GameTime,String Location1) {
        AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
         //创建请求参数的封装的对象
        RequestParams params = new RequestParams();
        params.put("TeamName", TeamName); // 设置请求的参数名和参数值
        params.put("Mana_id_main", Mana_id_main); // 设置请求的参数名和参数值
        params.put("Com_time", GameTime); // 设置请求的参数名和参数值
        params.put("Com_place", Location1); // 设置请求的参数名和参数值
        // 执行post方法
        RequestHandle post = client.get(url, params, new AsyncHttpResponseHandler() {
            /**
             * 成功处理的方法
             * statusCode:响应的状态码; headers:相应的头信息 比如 响应的时间，响应的服务器 ;
             * responseBody:响应内容的字节
             */
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  byte[] responseBody) {
                if (statusCode == 200) {
                    String str = new String(responseBody);
                    if (str.equals("error")) {
                        Toast.makeText(CreateGame.this,"您还没有球队先创建球队",Toast.LENGTH_SHORT).show();
                    } else {
                        Gson gson = new Gson();
                        List<MyTeam_name> list = new ArrayList<MyTeam_name>();
                        list = gson.fromJson(str,new TypeToken<ArrayList<MyTeam_name>>(){}.getType());
                        Teamname.clear();
                        for (int i = 0; i < list.size(); i++) {
                            Teamname.add(list.get(i).getTeam_name());
                        }
                        arr_adapter.notifyDataSetChanged();
                    }
                }
            }

            /**
             * 失败处理的方法
             * error：响应失败的错误信息封装到这个异常对象中
             */
            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  byte[] responseBody, Throwable error) {
                error.printStackTrace();// 把错误信息打印出轨迹来
                //Toast.makeText(MyApplication.getContext(), "网络错误", Toast.LENGTH_LONG).show();
            }
        });
    }
}
